package com.student.dms;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;

import androidx.fragment.app.Fragment;

import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.luck.picture.lib.utils.ToastUtils;
import com.student.db.AccountDao;
import com.student.db.AccountEntity;
import com.student.db.AppDatabase;
import com.student.dms.databinding.FragmentMineBinding;
import com.student.dms.databinding.FragmentStudentHomeBinding;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Single;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class MineFragment extends BaseFragment<FragmentMineBinding> {

    @Override
    public void setViewBinding() {
        mViewBinding = FragmentMineBinding.inflate(getLayoutInflater());
    }

    @Override
    public void init() {
        SharedPreferences sharedPreferences = requireActivity().getSharedPreferences("user", Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sharedPreferences.edit();
        String username = sharedPreferences.getString("username", "");
        mViewBinding.name.setText(username);
        mViewBinding.loginOut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
                builder.setCancelable(false);
                builder.setTitle("提醒");
                builder.setMessage("是否确定退出登录？");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        edit.putString("username","");
                        edit.putString("password","");
                        edit.commit();

                        startActivity(new Intent(requireActivity(),LoginActivity.class));
                        mViewBinding.loginOut.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                requireActivity().finish();
                            }
                        },300);
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.show();
            }
        });

        mViewBinding.accountSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(requireActivity(),ChangePasswordActivity.class));
            }
        });
        mViewBinding.infomation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(requireActivity(),ChangeInfoActivity.class));
            }
        });
        mViewBinding.portrait.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PictureSelector.create(requireActivity())
                        .openGallery(SelectMimeType.ofImage())
                        .setImageEngine(new GlideEngine())
                        .setMaxSelectNum(1)
                        .forResult(new OnResultCallbackListener<LocalMedia>() {
                            @Override
                            public void onResult(ArrayList<LocalMedia> result) {
                                LocalMedia localMedia = result.get(0);
                                AppDatabase roomDatabase = DMSApplication.getApplication().getRoomDatabase();
                                AccountDao accountDao = roomDatabase.provideAccountDao();
                                Single<AccountEntity> studentFlow = accountDao.searchAccountByName(username);
                                disposable.add(studentFlow.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(accountEntity -> {
                                    accountEntity.setPortraits(localMedia.getRealPath());
                                    disposable.add(accountDao.insert(accountEntity).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(() ->{
                                        //设置本地头像
                                        Bitmap bitmap = BitmapFactory.decodeFile(localMedia.getRealPath());
                                        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
                                        mViewBinding.portrait.setImageBitmap(bitmap);
                                        ToastUtils.showToast(requireActivity(), "头像更新成功！");
                                    } , insertstudentDaothrowable -> ToastUtils.showToast(requireActivity(), "头像更新失败！  message: " + insertstudentDaothrowable.getMessage())));
                                }, studentFlowThrowable -> {
                                    ToastUtils.showToast(requireActivity(), "用户不存在，请注册！");
                                }));
                            }

                            @Override
                            public void onCancel() {

                            }
                        });

            }
        });

        AppDatabase roomDatabase = DMSApplication.getApplication().getRoomDatabase();
        AccountDao accountDao = roomDatabase.provideAccountDao();
        Single<AccountEntity> studentFlow = accountDao.searchAccountByName(username);
        disposable.add(studentFlow.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(accountEntity -> {
            String portraits = accountEntity.getPortraits();
            if(!TextUtils.isEmpty(portraits) ){
                File file = new File(portraits);
                if(file.exists()){
                    Bitmap bitmap = BitmapFactory.decodeFile(portraits);
                    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
                    mViewBinding.portrait.setImageBitmap(bitmap);
                }
            }
        }, studentFlowThrowable -> {
            ToastUtils.showToast(requireActivity(), "用户不存在，请注册！");
        }));
    }
}
